package com.wyy.ems_vue.controller;/*
 **
 * @author yangyang
 *@date 2022/07/02 10:38
 **/

import com.wyy.ems_vue.entity.User;
import com.wyy.ems_vue.service.UserService;
import com.wyy.ems_vue.utils.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
@CrossOrigin
@Slf4j
public class UserController {
     @Autowired
     private UserService userService;

    @GetMapping("getImage")
    public  String getImageCode(HttpServletRequest request) throws  Exception{

        String code = VerifyCodeUtils.generateVerifyCode(4);
        request.getServletContext().setAttribute("code", code);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(220,80,byteArrayOutputStream,code);
        String s = "data:image/png;base64," +Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());
        return  s;
    }

    @PostMapping("register")
    public Map<String,Object> register(@RequestBody User user,String code,HttpServletRequest request){
        Map<String,Object> map=new HashMap<>();
        log.info("===注册==="+user.toString());
        try {
            String key = (String) request.getServletContext().getAttribute("code");
            log.info(code+"===验证码==="+key);
            if (key.equalsIgnoreCase(code)){
                userService.register(user);
                map.put("state", true);
                map.put("msg", "注册成功");

            }else {
               throw  new RuntimeException("验证码错误");
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", "注册失败");
        }
      return  map;
    }

    @PostMapping("login")
    public  Map<String,Object> login(@RequestBody User user){
        Map<String,Object> map=new HashMap<>();
        try {
            User login = userService.login(user);
            map.put("state", true);
            map.put("msg", "登录成功");
            map.put("user", login);
        }catch (Exception e){
           e.printStackTrace();
            map.put("state", false);
            map.put("msg", e.getMessage());
        }
        return map;
    }


}
